package com.lishe.lishe.lishe.module.launch.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.http.HttpUser;
import com.lishe.lishe.lishe.module.launch.adapter.ViewPagerAdapter;
import com.lishe.lishe.lishe.module.launch.view.GifView;
import com.lishe.lishe.lishe.module.main.activity.MainActivity0;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by zhcase on 2017/9/5.
 * 启动是的导航页
 */

public class LaunchActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    private static final String TAG = LaunchActivity.class.getSimpleName();

    private ViewPager viewPager;

    private int[] imageId = {R.mipmap.splash_1, R.mipmap.splash_2, R.mipmap.splash_3};
    private int[] imageBGId = {R.mipmap.splash_1_bg, R.mipmap.splash_2_bg, R.mipmap.splash_3_bg};
    private List<View> viewList;
    //private List<ImageUrlBean> imageList;

    private View lastView;

    //设置小圆点
    private ImageView[] points;//存放小圆圈数组

    private int currentIndex = 0;//当前页面,默认首

    private ImageView launch_image;

    private Animation animation;

//    private boolean isAutoLogined = false;

    private LinearLayout pointsLinearLayout;


    //使用Volley加载网络图片  这个版本不使用网络
//    private RequestQueue mQueue;
//    private ImageLoader mImageLoader;
//    ImageLoader.ImageListener imageListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        hideBottomUIMenu();
        setContentView(R.layout.activity_launch);
        initView();
        if (getSharePreferences()) {//首次登陆
            startAnimation();
            setSharePreferences();
            initViewPage();
            initPoints();
        } else {
            pointsLinearLayout.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(Globals.getToken())) {
                doTokenLogin();
            } else {
                intoMain(2000);
            }
        }
    }

    private void initView() {
        viewPager = findViewById(R.id.view_pager);
        launch_image = findViewById(R.id.launch_image);
        launch_image.setClickable(true);
        viewPager = findViewById(R.id.view_pager);
        pointsLinearLayout = findViewById(R.id.point_container);
    }

    /**
     * 登陆
     */
    private void doTokenLogin() {
        String token = Globals.getToken();
        HttpUser.getUpToken(token,null, responseHandler);
    }

    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String data = new String(responseBody);
            Log.e("跟新token", data);
            if (data != null) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                        String mtoken = jsonObject.optString("data");
                        String msg = jsonObject.optString("msg");
                        if (!TextUtils.isEmpty(mtoken) && !mtoken.equals("null")) {
                            Log.e("清空保存token", mtoken);
                            SharedPreferencesUtils.saveToken(mtoken, LaunchActivity.this);
                        } else {
                            Log.e("清空token", mtoken);
                            SharedPreferencesUtils.removeToken(LaunchActivity.this);
                        }
                    }else{
                        Log.e("清空token", "");
                        SharedPreferencesUtils.removeToken(LaunchActivity.this);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    SharedPreferencesUtils.removeToken(LaunchActivity.this);
                }
            }
            intoMain(2000);

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            SharedPreferencesUtils.removeToken(LaunchActivity.this);
            intoMain(2000);
        }
    };

    /**
     * 登陆成功后第一张图片一动画的形式透明隐藏
     */
    private void startAnimation() {
        animation = AnimationUtils.loadAnimation(this, R.anim.launch_gradually);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                launch_image.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        launch_image.startAnimation(animation);
    }

    @Override
    protected void onResume() {
        super.onResume();
        hideBottomUIMenu();
        hideNavigationBar();

    }

    @Override
    protected void onPause() {
        super.onPause();
        //showNavigationBar();
    }

    //这里是加载mipmap中图片的方式，初始化ViewPager及其图片资源
    private void initViewPage() {

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int top = Math.round((float) dm.heightPixels * (1265f / 1334f));
        viewList = new ArrayList<>();
        //添加对应的view进入集合（数据源）
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        for (int i = 0; i < imageId.length; i++) {
            RelativeLayout layout = new RelativeLayout(this);
            layout.setBackgroundResource(imageBGId[i]);
            layout.setLayoutParams(params);
            GifView imageView = new GifView(this);
            imageView.setLayoutParams(params);
            imageView.setMovieResource(imageId[i]);
            layout.addView(imageView);
            if (i == 0) {
                imageView.setPaused(false);
            } else {
                imageView.setPaused(true);
            }
            if (i == 2) {
                //加一个进入主页按钮
                ImageView launchToMain = new ImageView(this);
                launchToMain.setImageResource(R.mipmap.btn_launch_to_main);
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                //lp.topMargin = top;//px
                lp.bottomMargin = 25;//
                lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
                lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
                launchToMain.setLayoutParams(lp);
                launchToMain.setClickable(true);
                launchToMain.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        intoMain(0);
                    }
                });
                layout.addView(launchToMain);
            }
            viewList.add(layout);
        }

        //设置viewpager的适配器和数据源
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(viewList);
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setOnPageChangeListener(this);
    }


    private void intoMain(int time) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(LaunchActivity.this, MainActivity0.class));
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                finish();
            }
        }, time);


    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    //初始化下标点
    private void initPoints() {
        points = new ImageView[3];
        //初始化布局中的小圆点ImageView控件
        for (int i = 0; i < points.length; i++) {
            points[i] = (ImageView) pointsLinearLayout.getChildAt(i);//遍历LinearLayout下的所有ImageView子节点
            points[i].setEnabled(true);//设置当前状态为允许点击（可点，灰色）
            points[i].setOnClickListener(this);//设置点击监听
            //额外设置一个标识符，以便点击小圆点时跳转对应页面
            points[i].setTag(i);//标识符与圆点顺序一致
        }
        currentIndex = 0;
        points[currentIndex].setEnabled(false);//设置首页为当前页(不可点，黑色)
    }


    @Override
    public void onClick(View v) {
        viewPager.setCurrentItem((int) v.getTag());
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.point_container);

        //Log.e(TAG,"onPageScrolled:"+position+"  "+ positionOffset +"   "+positionOffsetPixels);
        if ((position == 1 && positionOffset >= 0.5f) || (position == 2)) {
            pointsLinearLayout.setVisibility(View.INVISIBLE);
            hideNavigationBar();
        } else {
            pointsLinearLayout.setVisibility(View.VISIBLE);
            hideNavigationBar();

        }


    }

    @Override
    public void onPageSelected(int position) {

        //当前页卡被选择时,position为当前页数
        points[position].setEnabled(false);//不可点击
        points[currentIndex].setEnabled(true);//恢复之前页面状态
        currentIndex = position;
        for (int i = 0; i < viewList.size(); i++) {
            GifView gif = ((GifView) (((ViewGroup) viewList.get(position)).getChildAt(0)));
            if (i == position) {
                gif.setPaused(false);
            } else {
                gif.setPaused(false);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

        // Log.e(TAG,"onPageScrollStateChanged.state:"+state);
    }

    /**
     * 对首次登录进行记录
     */

    private void setSharePreferences() {
        SharedPreferences firstLogin = getSharedPreferences(Globals.SHAREPREFERENCES_NAME, MODE_PRIVATE);
        SharedPreferences.Editor ed = firstLogin.edit();
        ed.putBoolean("isFirstLogin", false);
        ed.commit();
    }

    private boolean getSharePreferences() {
        SharedPreferences firstLogin = getSharedPreferences(Globals.SHAREPREFERENCES_NAME, MODE_PRIVATE);
        isFirstLogin = firstLogin.getBoolean("isFirstLogin", true);
        Log.e("首次登陆",isFirstLogin+"");
        return isFirstLogin;
    }

    /**
     * 对首次登录进行记录
     */
    boolean isFirstLogin = true;


}
